#!/usr/bin/env perl

BEGIN {
	push @INC,".." if -f "../pv3.pm";
	push @INC,$ENV{CODEMGR_LIBS} if exists($ENV{CODEMGR_LIBS});
}

use pv3;
use Getopt::Long;
use strict;
use Config;

$::ARG_pv=undef;
$::ARG_version=undef;
$::ARG_tag=undef;
$::ARG_allowopen=0;

sub usage {
	print "
Usage: pv3_addtag [-p DIR] [-v X] [-a] -t 'tag' file ...

The pv3_addtag allows a new tag to be associated with a 
particular version of a file. That tag must obviously not
be used with any other version. Multiple tags can be
added to a version is necessary - though tags must contain
alphanumerics and limited other characters.

The following arguments are supported:

-p  By default the file in question containing the versions is
    thought to exist in the current directory. Use this option
    to reference the version file kept elsewhere.
-v  Indicate the numeric version to tag. If not specified
    it defaults to the latest version.
-a  Allow open - checked out files are still tagged. If the
    content differs from any known versino, the latest version
    is assumed to be the version that is to be tagged.
-t  The tag to associate with the file.

Written by Simon Edwards, (C) 2006-2010 www.advantsys.co.uk
";
	exit 1;
}

if(!GetOptions(
	"allowopen"	=> \$::ARG_allowopen,
	"pv=s"		=> \$::ARG_pv,
	"version=s"	=> \$::ARG_version,
	"tag=s"		=> \$::ARG_tag,
	)) {
	usage;
}

if(defined($::ARG_pv)) {
	if(! -d dirname($::ARG_pv)) {
		die("Directory to use for pv file does not exist.");
	}
	if(! -f $::ARG_pv) {
		die("Filename specified for PV file does not exist.");
	}
}

#########################################################################
# Abort if --tag is not set - we need that at least!	Also complain	#
# if it contains the | character.					#
#########################################################################

if(!defined($::ARG_tag)) {
	usage;
}
if($::ARG_tag =~ /\|/) {
	print "ERROR: Tag can not contain the '|' character.\n";
	exit 1;
}

my %args=();
$args{VERSION}=$::ARG_version if defined($::ARG_version);
$args{TAG}=$::ARG_tag;
$args{PVFILE}=$::ARG_pv if defined($::ARG_pv);
$args{ALLOWOPEN}=1 if $::ARG_allowopen==1;

if($Config{osname} =~ /mswin/i) {
	my @F=();
	for my $cpat (@ARGV) {
		push @F,glob($cpat);
	}
	@ARGV=@F;
}

{
my @N=();
	for my $cfile (@ARGV) {
		next if -d $cfile;
		next if ! -e _;
		next if $cfile =~ /,pv$/;
		push @N,$cfile;
	}

	my $ok=0; my $fails=0;
	my $res=pv3::addtag(FILE=>[@N],%args);
	for my $cf (@$res) {
		my ($rc,$ver,$file)=(@{$cf});
		if($rc==-1) {
			print STDERR "ERROR: $file - $ver\n";
			$fails++;
		} elsif($rc==-2) {
			print STDERR "WARNING: $file - $ver\n";
		} else {
			$ok++;
			print "ADDTAG: $cf->[3] - Added to $cf->[1],$cf->[2]\n";
		}
	}

	exit(0) if $fails==0;
	exit(1);
}

